package com.qeegoo.b2bautozityp.moudle.goods.view;

//┏┓　　　┏┓ 
//┏┛┻━━━┛┻┓ 
//┃　　　　　　　┃ 　 
//┃　　　━　　　┃ 
//┃　┳┛　┗┳　┃ 
//┃　　　　　　　┃ 
//┃　　　┻　　　┃ 
//┃　　　　　　　┃ 
//┗━┓　　　┏━┛ 
//┃　　　┃  神兽保佑　　　　　　　　 
//┃　　　┃  代码无BUG！ 
//┃　　　┗━━━┓ 
//┃　　　　　　　┣┓ 
//┃　　　　　　　┏┛ 
//┗┓┓┏━┳┓┏┛ 
// ┃┫┫　┃┫┫ 
// ┗┻┛　┗┻┛

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.kelin.mvvmlight.messenger.Messenger;
import com.qeegoo.b2bautozityp.BR;
import com.qeegoo.b2bautozityp.R;
import com.qeegoo.b2bautozityp.adapter.GoodsAdapter;
import com.qeegoo.b2bautozityp.constant.Constants;
import com.qeegoo.b2bautozityp.databinding.FragmentGoodsManagerBinding;
import com.qeegoo.b2bautozityp.injector.component.DaggerOrderListFragmentComponent;
import com.qeegoo.b2bautozityp.injector.module.OrderListFragmentModule;
import com.qeegoo.b2bautozityp.moudle.base.BaseAdapter;
import com.qeegoo.b2bautozityp.moudle.base.LazyLoadFragment;
import com.qeegoo.b2bautozityp.moudle.goods.model.GoodsManagerBean;
import com.qeegoo.b2bautozityp.moudle.goods.viewmodel.GoodItemViewModel;
import com.qeegoo.b2bautozityp.moudle.goods.viewmodel.GoodsManagerViewModel;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import base.lib.util.NavigateUtils;

/**
 * Created by lk on 2017/9/20.
 */

public class GoodsManagerFragment extends LazyLoadFragment<FragmentGoodsManagerBinding> {

    @Inject
    LinearLayoutManager mLayuoutManager;

    @Inject
    GoodsManagerViewModel mViewModel;

    private int pageNo = 1;
    private int totalPages;
    private GoodsManagerBean resultData;
    private boolean isShowBtn;
    private BaseAdapter adapter;
    private List<String> selectArray = new ArrayList<>();
    private boolean isAllSelect;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_goods_manager;
    }

    @Override
    protected void initInjector() {
        DaggerOrderListFragmentComponent.builder().appComponent(getAppComponent()).orderListFragmentModule(new OrderListFragmentModule(this)).build().inject(this);
    }

    @Override
    protected void initViews() {
        int state = getArguments().getInt("state");
        mBinding.setViewModel(mViewModel);
        mViewModel.setFragmentType(state);
        mBinding.orderRv.setLayoutManager(mLayuoutManager);
        mBinding.swipeLayout.setColorSchemeResources(R.color.colorPrimary);
        mBinding.swipeLayout.setOnRefreshListener(() -> {
            mViewModel.getDatas("1", getCurrentGoodsType(), "");
        });
        mBinding.orderRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    int lastVisiblePosition = linearLayoutManager.findLastVisibleItemPosition();
                    if (lastVisiblePosition >= linearLayoutManager.getItemCount() - 1) {
                        if (pageNo < totalPages) {
                            mViewModel.getDatas(++pageNo + "", getCurrentGoodsType(), "");
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

            }

        });
        adapter = new GoodsAdapter(BR.goodsAdapter, R.layout.adapter_goods_manager, new ArrayList<GoodItemViewModel>());
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            GoodItemViewModel viewModel = (GoodItemViewModel) adapter.getItem(position);
            String goodId = viewModel.detailBean.id;
            Bundle bundle = new Bundle();
            bundle.putString(Constants.Param_id,goodId);
            NavigateUtils.startActivity(GoodsDetailActivity.class,bundle);
        });
        mBinding.orderRv.setAdapter(adapter);
        mViewModel.setAdapterInterface(data -> {


            resultData = data;
            List<GoodItemViewModel> datas = new ArrayList<GoodItemViewModel>();
            ;

            if (mBinding.swipeLayout != null) {
                mBinding.swipeLayout.setRefreshing(false);

            }
            if (data.list == null || data.list.size() == 0) {
                mViewModel.emptyVisible.set(View.VISIBLE);
            } else {
                int position = 0;
                for (GoodsManagerBean.GoodDetailBean detailBean : data.list) {
                    boolean isShowSelect = selectArray.contains(detailBean.id);
                    detailBean.isShowStatus = false;
                    detailBean.isShowBtn = isShowBtn;
                    detailBean.isSelect = isShowSelect;
                    detailBean.goodsStatusType = state;
                    detailBean.position = position++;
                    datas.add(new GoodItemViewModel(detailBean,mViewModel.requestApi,adapter));
                }
                mViewModel.emptyVisible.set(View.GONE);
            }
            if (data.curPageNo == 1) {
                adapter.replaceData(datas);
            } else {
                adapter.addData(datas);
            }
            totalPages = data.totalPages;
            pageNo = data.curPageNo;
            mViewModel.setArray(selectArray,adapter.getItemCount());
        });

        //接受 批量管理通知
        Messenger.getDefault().register(this, GoodsManagerFragment.class.getSimpleName(), GoodsManagerViewModel.GoodsPageData.class, data -> {
            int type = data.dataType;
            List<GoodItemViewModel> origin = adapter.getData();
            if (type == 1) {
                isShowBtn = data.dataBoolean;

                for (GoodItemViewModel itemViewModel : origin) {
                    itemViewModel.isVisible.set(data.dataBoolean ? View.VISIBLE : View.GONE);
                }
                mBinding.layoutBottom.setVisibility(isShowBtn?View.VISIBLE:View.GONE);
            } else if(type  == 2) {
                isAllSelect = data.dataBoolean;
                for (GoodItemViewModel itemViewModel : origin) {
                    itemViewModel.isSelected.set(data.dataBoolean);
                    itemViewModel.detailBean.isSelect = data.dataBoolean;
                    saveOrDelId(itemViewModel.detailBean);

                }
            }else {
                isShowBtn = data.dataBoolean;
                for (GoodItemViewModel itemViewModel : origin) {
                    itemViewModel.isVisible.set(data.dataBoolean ? View.VISIBLE : View.GONE);
                    itemViewModel.detailBean.isSelect = data.dataBoolean;
                    itemViewModel.isSelected.set(data.dataBoolean);
                }
                mBinding.layoutBottom.setVisibility(isShowBtn?View.VISIBLE:View.GONE);
                //全选按钮
                selectArray.clear();
                isAllSelect = false;
            }
            mViewModel.setArray(selectArray,origin.size());
            adapter.setNewData(origin);
        });
        //选中某个Item 接收器
        Messenger.getDefault().register(this, GoodsManagerFragment.class.getSimpleName(), GoodsManagerBean.GoodDetailBean.class, data -> {

            saveOrDelId(data);
        });
    }

    private void saveOrDelId(GoodsManagerBean.GoodDetailBean data) {
        if (!selectArray.contains(data.id)) {
            selectArray.add(data.id);
        } else {
            boolean has = data.isSelect;
            if (!has) {
                selectArray.remove(data.id);
            }
        }

        mViewModel.setArray(selectArray,adapter.getItemCount());
    }

    private String getCurrentGoodsType() {
        if (getArguments() != null) {
            return getArguments().getInt("state") + "";
        }
        return "1";
    }

    @Override
    public void requestData() {
        mBinding.swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                mBinding.swipeLayout.setRefreshing(true);
            }
        });
        mViewModel.getDatas("1", getCurrentGoodsType(), "");

    }

    public static LazyLoadFragment newInstance(int state) {
        GoodsManagerFragment goodsManagerFragment = new GoodsManagerFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("state", state);
        goodsManagerFragment.setArguments(bundle);
        return goodsManagerFragment;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Messenger.getDefault().unregister(this);
    }
}
